package com.example.demo.controller;

import com.example.demo.model.Student;

import com.example.demo.model.Teacher;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;

import java.util.List;

@Controller

@RequestMapping("teacher")

public class TeacherController {

    private static List<Teacher> teacherList = new ArrayList<>();

    static {

        Teacher s1 = new Teacher();

        s1.setId(1);

        s1.setName("TomT");

        teacherList.add(s1);

        Teacher s2 = new Teacher();

        s2.setId(2);

        s2.setName("JerryT");

        teacherList.add(s2);

    }

    @RequestMapping("list")

    public String list(ModelMap modelMap) {

        modelMap.put("teacherList", teacherList);

        return "teacher/list";

    }

    @RequestMapping("delete/{id}")

    public String delete(@PathVariable Integer id) {

        teacherList.remove(id - 1);

        return "redirect:/teacher/list";

    }

    @RequestMapping("save")

    public String save(Teacher s) {

        s.setId(teacherList.size() + 1);

        teacherList.add(s);

        return "redirect:/teacher/list";

    }

    @RequestMapping("edit/{id}")

    public String edit(@PathVariable Integer id, ModelMap map) {

        Teacher s = teacherList.get(id - 1);

        map.put("teacher", s);

        return "teacher/edit";

    }

    @RequestMapping("update")

    public String update(Teacher s) {

        for (Teacher teacher: teacherList) {

            if (teacher.getId().equals(s.getId())) {
                teacher.setName(s.getName());

            }

        }

        return "redirect:/teacher/list";

    }

}

